const base_url = "http://localhost:50000/api";
const request = {
    get: (path, params = {}) => {
        return new Promise((resolve, reject) => {
            uni.request({
                url: base_url + path + "?" + new URLSearchParams(params).toString(),
                method: "GET",
                header: {
                    "Content-Type": "application/json",
                    "Authorization": "Bearer " + uni.getStorageSync("token")
                },
                success: (res) => {
                    if (res.statusCode === 200) {
                        resolve(res.data); // 请求成功，返回数据
                    } else {
                        reject(new Error('请求失败，状态码：' + res.statusCode));
                    }
                },
                fail: (error) => {
                    reject(error); // 请求失败
                }
            });
        });
    },
    post: (path, params = {}) => {
        return new Promise((resolve, reject) => {
            uni.request({
                url: base_url + path,
                method: "POST",
                header: {
                    "Content-Type": "application/json",
                    "Authorization": "Bearer " + uni.getStorageSync("token")
                },
                data: params,
                success: (res) => {
                    if (res.statusCode === 200) {
                        resolve(res.data); // 请求成功，返回数据
                    } else {
                        reject(new Error('请求失败，状态码：' + res.statusCode));
                    }
                },
                fail: (error) => {
                    reject(error); // 请求失败
                }
            });
        });
    }
}

const message = {
    success: (message) => {
        uni.showToast({
            title: message,
            icon: 'success', // 不显示图标
            duration: 2000
        })
    },
    error: (message) => {
        uni.showToast({
            title: message,
            icon: 'error', // 不显示图标
            duration: 2000
        });
    }
}

const back = () => {
    const pages = getCurrentPages();
    // 如果只有当前页退回主页
    if (pages.length <= 1) {
        uni.navigateTo({
            url: "/"
        });
    } else {
        // 如果有多个页面依次退回直到页面不重复或长度为1
        const prevPage = pages[pages.length - 2]; // 上一个页面
        const curPage = pages[pages.length - 1]; //  当前页面
        if (prevPage.route === curPage.route) {
            uni.navigateBack();
            back();
        } else {
            uni.navigateBack();
        }
    }
}


export {
    request,
    message,
    back
};